package com.ws.universal.tools.takephoto.multipleimageselect.activities;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.gyf.barlibrary.ImmersionBar;
import com.ws.universal.tools.R;
import com.ws.universal.tools.RequestCode;
import com.ws.universal.tools.pictureselect.manage.CollectionManage;
import com.ws.universal.tools.pictureselect.media.MediaFile;
import com.ws.universal.tools.pictureselect.task.LoadAllTask;
import com.ws.universal.tools.pictureselect.task.LoadImageTask;
import com.ws.universal.tools.pictureselect.task.MediaCallBack;
import com.ws.universal.tools.takephoto.multipleimageselect.adapters.CustomImageSelectAdapter;
import com.ws.universal.tools.takephoto.multipleimageselect.helpers.ConstantsCode;
import com.ws.universal.tools.takephoto.multipleimageselect.models.ImageBean;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.ToastUtils;

import java.io.File;
import java.util.ArrayList;

/**
 * @author:ws
 * @date: 2020/9/1 14:26
 * @desc 选取图片
 */
public class ImageSelectActivity extends AppCompatActivity {
    private final String[] requiredPermissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
    private ArrayList<ImageBean> images;
    private String album;
    private GridView gridView;
    private CustomImageSelectAdapter adapter;
    private ProgressBar progressBar;
    private int countSelected;
    private TextView title_text_tv;
    private TextView title_right_btn;
    private Handler handler;
    private boolean showVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //沉浸式
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        setContentView(R.layout.activity_image_select);

        title_text_tv = findViewById(R.id.title_text_tv);
        title_text_tv.setText(getResources().getString(R.string.image_view));
        title_right_btn = findViewById(R.id.title_right_btn);

        findViewById(R.id.title_left_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent == null) {
            finish();
        }
        album = intent.getStringExtra(ConstantsCode.INTENT_EXTRA_ALBUM);

        showVideo = intent.getBooleanExtra(ConstantsCode.showVideo, false);

        progressBar = findViewById(R.id.progress_bar_image_select);
        gridView = findViewById(R.id.grid_view_image_select);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LogcatUtils.i("" + images.get(position).type);
                if (checkVideo()) {
                    if (images.get(position).isSelected) {
                        toggleSelection(position);
                        title_text_tv.setText(countSelected + " " + getResources().getString(R.string.selected));
                        title_right_btn.setText(getResources().getString(R.string.add));
                        title_right_btn.setVisibility(View.VISIBLE);
                    } else {
                        //ToastUtils.showShort("不能同时选择视频和图片");
                        LogcatUtils.e("不能同时选择视频和图片");
                    }
                    return;
                } else {
                    if (checkImage()) {
                        if (images.get(position).type.equals("video/mp4")) {
                            //ToastUtils.showShort("不能同时选择视频和图片");
                            LogcatUtils.e("不能同时选择视频和图片");
                            return;
                        }
                    }
                }
                toggleSelection(position);
                title_text_tv.setText(countSelected + " " + getResources().getString(R.string.selected));
                title_right_btn.setText(getResources().getString(R.string.add));
                title_right_btn.setVisibility(View.VISIBLE);

            }
        });

        title_right_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendIntent();
            }
        });

        initData();
    }

    private boolean checkVideo() {
        for (int i = 0; i < images.size(); i++) {
            if (images.get(i).type.equals("video/mp4") && images.get(i).isSelected) {
                return true;
            }
        }
        return false;

    }

    private boolean checkImage() {
        for (int i = 0; i < images.size(); i++) {
            if (images.get(i).isSelected) {
                return true;
            }
        }
        return false;

    }

    @Override
    protected void onStart() {
        super.onStart();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case ConstantsCode.PERMISSION_DENIED: {
                        progressBar.setVisibility(View.INVISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }

                    case ConstantsCode.FETCH_STARTED: {
                        progressBar.setVisibility(View.VISIBLE);
                        gridView.setVisibility(View.INVISIBLE);

                        break;
                    }
                    case ConstantsCode.FETCH_COMPLETED: {
                        if (adapter == null) {
                            adapter = new CustomImageSelectAdapter(getApplicationContext(), images);
                            gridView.setAdapter(adapter);
                            progressBar.setVisibility(View.INVISIBLE);
                            gridView.setVisibility(View.VISIBLE);
                            orientationBasedUI(getResources().getConfiguration().orientation);

                        } else {
                            adapter.notifyDataSetChanged();
                            /*
                            Some selected images may have been deleted
                            hence update action mode title
                             */
                            title_text_tv.setText(countSelected + " " + getResources().getString(R.string.selected));
                        }

                        break;
                    }
                    case ConstantsCode.ERROR: {
                        progressBar.setVisibility(View.INVISIBLE);
                    }
                }
            }
        };

    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == ConstantsCode.PERMISSION_REQUEST_READ_EXTERNAL_STORAGE) {
            Message message = handler.obtainMessage();
            message.what = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ? ConstantsCode.PERMISSION_GRANTED : ConstantsCode.PERMISSION_DENIED;
            message.sendToTarget();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


        images = null;
        if (adapter != null) {
            adapter.releaseResources();
        }
        gridView.setOnItemClickListener(null);
    }


    private void orientationBasedUI(int orientation) {
        final WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        final DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);

        if (adapter != null) {
            int size = orientation == Configuration.ORIENTATION_PORTRAIT ? metrics.widthPixels / 3 : metrics.widthPixels / 5;
            adapter.setLayoutParams(size);
        }
        gridView.setNumColumns(orientation == Configuration.ORIENTATION_PORTRAIT ? 3 : 5);
    }


    private void toggleSelection(int position) {

        if (ConstantsCode.limit > 1) {
            //多选
            if (!images.get(position).isSelected && countSelected >= ConstantsCode.limit) {
                //Toast.makeText(getApplicationContext(), String.format(getString(R.string.limit_exceeded), ConstantsCode.limit), Toast.LENGTH_SHORT).show();
                ToastUtils.showShort(String.format(getResources().getString(R.string.limit_exceeded), ConstantsCode.limit));
                return;
            }

            images.get(position).isSelected = !images.get(position).isSelected;
            if (images.get(position).isSelected) {
                countSelected++;
            } else {
                countSelected--;
            }


        } else {
            //单选
            for (int i = 0; i < images.size(); i++) {
                if (i == position) {
                    images.get(position).isSelected = true;
                } else {
                    images.get(i).isSelected = false;
                }
            }
            countSelected = 1;

        }

        adapter.notifyDataSetChanged();
    }


    private ArrayList<ImageBean> getSelected() {
        ArrayList<ImageBean> selectedImages = new ArrayList<>();
        for (int i = 0, l = images.size(); i < l; i++) {
            if (images.get(i).isSelected) {
                selectedImages.add(images.get(i));
            }
        }
        return selectedImages;
    }

    private void sendIntent() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(ConstantsCode.INTENT_EXTRA_IMAGES, getSelected());
        //intent.putStringArrayListExtra(Constants.INTENT_EXTRA_IMAGES, getSelected());
        setResult(RequestCode.RequestCode_Photo, intent);
        finish();
    }


    /**
     * 获取数据
     */
    private void initData() {

        Runnable runnableTask = null;

        if (!showVideo) {//只加载图片
            //
            runnableTask = new LoadImageTask(this, new CallBackData());
            //        } else if (showVideo && !showImage) {//只加载视频
            //            runnableTask = new LoadVideoTask(this, new CallBackData());

        } else if (runnableTask == null) {//全部加载
            runnableTask = new LoadAllTask(this, new CallBackData());
        }
        new Thread(runnableTask).start();
    }

    class CallBackData implements MediaCallBack {

        @Override
        public void resultArrayList(final ArrayList<MediaFile> list) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    CollectionManage.getInstance().setAllList(list);
                    Message message;
                    if (adapter == null) {
                        message = handler.obtainMessage();

                        message.what = ConstantsCode.FETCH_STARTED;
                        message.sendToTarget();
                    }

                    if (Thread.interrupted()) {
                        return;
                    }

                    //                    File file;
                    //                    HashSet<Long> selectedImages = new HashSet<>();
                    //                    if (images != null) {
                    //                        Image image;
                    //                        for (int i = 0, l = images.size(); i < l; i++) {
                    //                            image = images.get(i);
                    //                            file = new File(image.path);
                    //                            if (file.exists() && image.isSelected) {
                    //                                selectedImages.add(image.id);
                    //                            }
                    //                        }
                    //                    }


                    ArrayList<ImageBean> temp = new ArrayList<>();

                    File file;
                    for (int i = 0; i < list.size(); i++) {
                        long id = list.get(i).getBucket_id();
                        String name = list.get(i).getFolderName();
                        String path = list.get(i).getPath();
                        String type = list.get(i).getMime();
                        long time = list.get(i).getDuration();
                        file = new File(path);
                        if (file.exists() && name.contains(album)) {
                            temp.add(new ImageBean(id, path, time, type, false));
                        }
                    }

                    if (images == null) {
                        images = new ArrayList<>();
                    }
                    images.clear();
                    images.addAll(temp);

                    message = handler.obtainMessage();
                    message.what = ConstantsCode.FETCH_COMPLETED;
                    //                    message.arg1 = tempCountSelected;
                    message.sendToTarget();
                }
            });

        }
    }


}
